$:.unshift File.join(File.dirname(__FILE__))
require 'test_helper'

class TestDice < Test::Unit::TestCase
  
  def test_keys 
    d = Yahtzee::Dice.new
    d.roll
    assert_equal([1,2,3,4,5,6], d.to_hash.keys.sort)
  end
    
  def test_roll_randomness
     count = {}
     roll = 1000
     1..roll.times do 
        d = Yahtzee::Dice.new
        d.roll
        count.add_values!(d.to_hash)
     end

     count.each do |key, value|
        percentage = ( value.to_f / ( count.size * roll ) ) * 100
        assert( percentage > 14 )
        assert( percentage < 18 )
     end         
  end
  
  def test_dice_total
     count = {}
     roll = 1000
     1..roll.times do
        dice = Yahtzee::Dice.new
        dice.roll
        sum = dice.to_hash.values.sum
        assert sum >= 6
        assert sum <= 36
     end
  end

  def test_roll_six
    d = Yahtzee::Dice.new
    d.roll
    assert_equal( 6, d.to_hash.values.sum )     
  end
  
  def test_keep_1
     d = { 2 => 1, 1 => 0, 5 => 0, 6 => 0 }
     dice = Yahtzee::Dice.new(d)
     dice.roll([2])
     assert( dice.to_hash[2] >= 1 )
  end

  def test_keep_2
     d = { 2 => 2, 1 => 0, 5 => 0, 6 => 0 }
     dice = Yahtzee::Dice.new(d)
     dice.roll([2])
     assert( dice.to_hash[2] >= 2 )
  end

  def test_keep_all
     d = { 2 => 2, 1 => 0, 5 => 0, 6 => 0 }
     dice = Yahtzee::Dice.new(d)
     dice.roll(d.keys)
     assert_equal( d, dice.to_hash )
  end

  def test_rank_total
    result = Yahtzee::Dice.new.roll
    total = 0
    result.each do |k,v|
      total += k * v.size
    end
    assert_equal( 6, total )
  end

  def test_yahtzee_true
    d = Yahtzee::Dice.new({1 => 6, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0})
    assert d.yahtzee?  
  end

  def test_yahtzee_false
    d = Yahtzee::Dice.new({1=>5})
    assert !d.yahtzee?  
  end

  def test_die_count_exists
    count = 6
    die = 1
    d = Yahtzee::Dice.new({die => count})
    assert_equal(count, d.die_count(die))
  end

  def test_die_count_not_exits
    count = 6
    die = 1
    d = Yahtzee::Dice.new({die => count})
    assert_equal(0, d.die_count(die + 1))
  end

end

class Hash

   def add_values!( hsh )
      hsh.each do |k,v|
          if self.include? k
              self[k] += v
          else
              self[k] = v
          end
      end   
   end

end